package cn.manyufun.myf.common.webview;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.net.URI;

import cn.manyufun.myf.BuildConfig;

/**
 * Created by Xiao on 2018-02-12.
 */

public class WebServerViewClient extends WebViewClient {
    public static final String TAG = "xwx_WebViewClient";

    public Context mContext = null;
    public WebView mWebView = null;
    public BaseWebView mBaseWebView = null;

    public WebServerViewClient(Context context, BaseWebView webView) {
        mContext = context;
        mWebView = webView.webView;
        mBaseWebView = webView;
    }


    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        try {
            url = url.replaceAll(" ", "%20");
            URI uri = new URI(url);
            Log.i("xwx_url", url);
            Scheme scheme = new Scheme(uri, (Activity) mContext);
            if (scheme.isMYF()) {
                return true;
            } else if (!scheme.isHttp()) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                mContext.startActivity(intent);
                return true;
            }
//            Map<String, String> map = CommonUtils.GetExtraHttpRequestHeader(url);
//            view.loadUrl(url, map);
            view.loadUrl(url);
            return true;
        } catch (Exception e) {
            return true;
        }
    }


    private void disJsEvent(WebView view, String eventName) {
        String js = "javascript:(" +
                "function(){" +
                "var e = document.createEvent('Event');" +
                "e.initEvent('" + eventName + "',true,true);" +
                "document.dispatchEvent(e);" +
                "}" +
                ")()";
        view.loadUrl(js);
    }

    @Override
    public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
//            handler.proceed(); // Ignore SSL certificate errors
        String url = view.getUrl();
        if (url.contains("jjcbw")) {
            handler.proceed();
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        AlertDialog alertDialog = builder.create();
        String message = "SSL Certificate error.";
        switch (error.getPrimaryError()) {
            case SslError.SSL_UNTRUSTED:
                message = "The certificate authority is not trusted.";
                break;
            case SslError.SSL_EXPIRED:
                message = "The certificate has expired.";
                break;
            case SslError.SSL_IDMISMATCH:
                message = "The certificate Hostname mismatch.";
                break;
            case SslError.SSL_NOTYETVALID:
                message = "The certificate is not yet valid.";
                break;
        }

        message += " Do you want to continue anyway?";
        alertDialog.setTitle("SSL Certificate Error");
        alertDialog.setMessage(message);
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Ignore SSL certificate errors
                handler.proceed();
            }
        });

        alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                handler.cancel();
            }
        });
        alertDialog.show();

    }

    @Override
    public void onPageFinished(WebView view, String url) {
        Log.i("xwx_pagefinish", url);
        view.getSettings().setBlockNetworkImage(false);
        if (BuildConfig.DEBUG)
            mWebView.loadUrl("javascript:(function(e){e.setAttribute(\"src\",\"http://192.168.1.2:8080/target/target-script-min.js#anonymous\");document.getElementsByTagName(\"body\")[0].appendChild(e);})(document.createElement(\"script\"));void(0);");

    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        Log.i("xwx_pagestart", url);
    }


    @Override
    public void onScaleChanged(WebView view, float oldScale, float newScale) {
        super.onScaleChanged(view, oldScale, newScale);
        view.requestFocus();
        view.requestFocusFromTouch();
    }
}